import { contextBridge, ipcRenderer, OpenDialogOptions } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'
import type { ApiType } from '../preload/index.d'

// Custom APIs for renderer
const api: ApiType = {
  // 暴露设置标题方法
  setTitle: (title: string) => ipcRenderer.send('set-title', title),
  // 选择文件
  chooseFiles: (values?: OpenDialogOptions) => ipcRenderer.invoke('choose-files', values) as any,
  // 打开某个特定页面
  openPage: (page) => ipcRenderer.on('open-page', page),
  // 选择目录
  chooseOpenDirectory: () => ipcRenderer.invoke('dialog:openDirectory') as any,
  // 返回文件流
  getFileStreamByPath: (values: { filePath: string }[]) => ipcRenderer.invoke('file:getFileStreamByPath', values) as any,
  // 获取存储值
  getStoreValue: (key: string) => ipcRenderer.invoke('store:getStoreValue', key) as any,
  // 设置单个存储值
  setStoreValue: (key: string, value: any) => ipcRenderer.invoke('store:setStoreValue', key, value) as any,
  // 设置多个存储值
  setStoreValues: (values) => ipcRenderer.invoke('store:setStoreValues', values) as any,
  // 删除存储值
  deleteStoreValue: (key: string) => ipcRenderer.invoke('store:deleteStoreValue', key) as any,
  // 删除所有
  deleteAllStoreValue: () => ipcRenderer.invoke('store:deleteAllStoreValue') as any,
  // 是否有某个属性
  hasStoreValue: (key: string) => ipcRenderer.invoke('store:hasStoreValue', key) as any,
  // pdf 转换为图片
  pdfToImg: (paths: any[]) => ipcRenderer.invoke('convert:pdfToImg', paths) as any,
  // pdf 转换为word
  pdfToWord: (paths: any[]) => ipcRenderer.invoke('convert:pdfToWord', paths) as any,
  // ppt转pdf
  pptToPdf: (paths: any[]) => ipcRenderer.invoke('convert:pptToPdf', paths) as any,
  // wordToPdf转pdf
  wordToPdf: (paths: any[]) => ipcRenderer.invoke('convert:wordToPdf', paths) as any,
  // wordToPdf转pdf
  excelToPdf: (paths: any[]) => ipcRenderer.invoke('convert:excelToPdf', paths) as any,
  // wordToPdf转pdf
  extractResources: (paths: any[]) => ipcRenderer.invoke('handle:extractResources', paths) as any,
  // pdf 压缩
  compress: (paths: any[]) => ipcRenderer.invoke('handle:compress', paths) as any,
}

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI)
    contextBridge.exposeInMainWorld('api', api)
  } catch (error) {
    console.error(error)
  }
} else {
  // @ts-ignore (define in dts)
  window.electron = electronAPI
  // @ts-ignore (define in dts)
  window.api = api
}
